import { ref } from 'vue'

export function useTransform(getCanvas) {
  // 旋转图片
  const rotateImage = (angle) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject) return

    // 如果传入的是增量角度，则在当前角度基础上增加
    if (typeof angle === 'string' && angle.startsWith('+')) {
      const increment = parseFloat(angle.slice(1))
      activeObject.rotate((activeObject.angle || 0) + increment)
    } else {
      activeObject.rotate(angle)
    }

    fabricCanvas.renderAll()
  }

  // 翻转图片
  const flipImage = (direction) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject) return

    if (direction === 'horizontal') {
      activeObject.set('flipX', !activeObject.flipX)
    } else if (direction === 'vertical') {
      activeObject.set('flipY', !activeObject.flipY)
    }

    fabricCanvas.renderAll()
  }

  // 调整图片大小
  const resizeImage = (scale) => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject) return

    activeObject.scale(scale)
    fabricCanvas.renderAll()
  }

  // 重置变换
  const resetTransform = () => {
    const fabricCanvas = getCanvas()
    if (!fabricCanvas) return

    const activeObject = fabricCanvas.getActiveObject()
    if (!activeObject) return

    activeObject.set({
      scaleX: 1,
      scaleY: 1,
      angle: 0,
      flipX: false,
      flipY: false
    })

    fabricCanvas.renderAll()
  }

  return {
    rotateImage,
    flipImage,
    resizeImage,
    resetTransform
  }
} 